package top.zhangjianyong.netty.netty.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ctx.channel().eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("thread:"+Thread.currentThread().getName());
                    Thread.currentThread().sleep(2000);
                    System.out.println("done");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        ctx.channel().eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("thread:"+Thread.currentThread().getName());
                    Thread.currentThread().sleep(1000);
                    System.out.println("done");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("thread:"+Thread.currentThread().getName());
                    Thread.currentThread().sleep(1000);
                    System.out.println("done222");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },5, TimeUnit.SECONDS);

        System.out.println("ctx:" + ctx);
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("msg:" + byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("ip:" + ctx.channel().remoteAddress());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,asd", CharsetUtil.UTF_8));
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup();

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
